package persistence

import (
	"context"
	"errors"
	"example.com/m/v2/internal/domain/account_aggregate/entity"
	"example.com/m/v2/internal/domain/account_aggregate/repository"
	"gorm.io/gorm"
	"log"
)

type subAccountRepository struct {
	db *gorm.DB
}

func (repo *subAccountRepository) Migrate() error {
	err := repo.db.AutoMigrate(&SubordinateAccountPo{})
	if err != nil {
		return err
	}
	return nil
}

func (repo *subAccountRepository) Save(context context.Context, entity *entity.SubAccountEntity) (*entity.SubAccountEntity, error) {
	if entity == nil {
		return nil, errors.New("not allow to save an null entity")
	}
	po := SubordinateAccountPo{}
	err := po.FromEntity(entity)
	if err != nil {
		return nil, err
	}
	repo.db.Create(&po)
	return po.ToEntity()
}

func NewSubAccountRepository(db *gorm.DB) repository.SubAccountRepository {
	log.Printf("sub account repository constructed")
	return &subAccountRepository{db}
}
